<template>
  <el-dialog
    title="基础信息"
    :visible.sync="open"
    width="500px"
    append-to-body
    @close="closeDialog"
    class="business-dialog"
  >
    <el-form :model="info" ref="queryForm" label-width="100px" size="small" :rules="rules">
      <el-form-item label="基础规范" prop="baseRuleId" v-show="selectVisible">
        <el-select v-model="info.baseRuleId" placeholder="请选择" clearable style="width: 100%">
          <el-option v-for="item in ruleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="规范名称" prop="name">
        <el-input v-model="info.name" placeholder="请输入" clearable maxlength="50" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="open = false">取消</el-button>
      <el-button type="primary" size="small" @click="handleSubmit" :loading="loading">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { Message } from 'element-ui'
import { handleRuleInfo } from '@/api/business'

const NameRule = [
  { required: true, message: '请输入规范名称', trigger: 'blur' },
  { pattern: /\s*\S+?/, message: '请输入非空字符', trigger: 'blur' }
]
const IDRule = [{ required: true, message: '请选择基础规范', trigger: 'blur' }]

export default {
  name: 'RulesEditModal',
  props: {
    editData: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    },
    ruleList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    visible(val) {
      this.open = val
      if (val) {
        this.$nextTick(() => this.$refs.queryForm?.clearValidate())
      }
    },
    editData(val) {
      this.info = JSON.parse(JSON.stringify(val))
      if (val.name) {
        this.rules = { name: NameRule }
      } else {
        this.rules = { name: NameRule, baseRuleId: IDRule }
      }
    }
  },
  computed: {
    selectVisible() {
      return !this.editData?.name && this.open
    }
  },
  data() {
    return {
      open: this.visible,
      info: {},
      rules: {
        name: NameRule,
        baseRuleId: IDRule
      },
      loading: false
    }
  },
  methods: {
    closeDialog() {
      this.info = {}
      this.$emit('update:visible', false)
      this.$emit('onClose')
    },
    handleSubmit() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.info))
          if (this.editData?.name) {
            params.id = this.editData.id
          }
          this.loading = true
          handleRuleInfo(params, this.editData?.name ? 'put' : 'post')
            .then((res) => {
              this.loading = false
              this.open = false
              Message.success('保存成功')
              this.$emit('onSuccess')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
